package gowx

import (
	"encoding/xml"
	"time"
)

type RecvXMLStruct struct {
	XMLName      xml.Name `xml:`
	ToUserName   string   `xml:"ToUserName"`
	FromUserName string   `xml:"FromUserName"`
	CreateTime   string   `xml:"CreateTime"`
	MsgType      string   `xml:"MsgType"`
	Event        string   `xml:"Event"`
	EventKey     string   `xml:"EventKey"`
	Latitude     string   `xml:"Latitude"`
	Ticket       string   `xml:"Ticket"`
	Longitude    string   `xml:"Longitude"`
	Precision    string   `xml:"Precision"`
	Content      string   `xml:"Content"`
	MsgID        string   `xml:"MsgId"`
	PicURL       string   `xml:"PicUrl"`
	MediaID      string   `xml:"MediaId"`
	Format       string   `xml:"Format"`
	Recognition  string   `xml:"Recognition"`
	ThumbMediaID string   `xml:"ThumbMediaId"`
	LocationX    string   `xml:"Location_X"`
	LocationY    string   `xml:"Location_Y"`
	Scale        string   `xml:"Scale"`
	Label        string   `xml:"Label"`
	Title        string   `xml:"Title"`
	Description  string   `xml:"Description"`
	URL          string   `xml:"Url"`
}

type ArticlesListXMLStruct struct {
	XMLName     string `xml:"item"`
	Title       string
	Description string
	PicURL      string `xml:"PicUrl"`
	URL         string `xml:"Url"`
}

type ArticlesXMLStruct struct {
	Item []ArticlesListXMLStruct
}

type NewsXMLStruct struct {
	XMLName      xml.Name `xml:"xml"`
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	ArticleCount int
	Articles     ArticlesXMLStruct
}

type TextXMLStruct struct {
	XMLName      xml.Name `xml:"xml"`
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	Content      string
}

func GetMSG(body []byte) (*RecvXMLStruct, error) {
	v := &RecvXMLStruct{}
	err := xml.Unmarshal(body, v)
	if err == nil {
		return v, nil
	}

	return v, err
}

func CreateTextXML(rxs *RecvXMLStruct, content string) string {
	s := &TextXMLStruct{
		ToUserName:   rxs.FromUserName,
		FromUserName: rxs.ToUserName,
		CreateTime:   time.Now().Unix(),
		MsgType:      "text",
		Content:      content,
	}
	b, _ := xml.Marshal(s)
	return string(b)
}

func CreateNewsXML(rxs *RecvXMLStruct, ArticleCount int, Articles []ArticlesListXMLStruct) string {
	s := &NewsXMLStruct{
		ToUserName:   rxs.FromUserName,
		FromUserName: rxs.ToUserName,
		CreateTime:   time.Now().Unix(),
		MsgType:      "news",
		ArticleCount: ArticleCount,
		Articles:     ArticlesXMLStruct{Articles},
	}
	b, _ := xml.Marshal(s)
	return string(b)
}
